<?php

namespace App\Repositories;

use App\Models\District;
use Illuminate\Support\Facades\Redis;

class DistrictRepository extends BaseRepository
{
    /**
     *  REDIS_EXPIRES_FOR_WEEKS 缓存有效期一周
     */
    const REDIS_EXPIRES_FOR_WEEKS = 604800;

    public function model()
    {
        return District::class;
    }

    /**
     * 获取区县列表
     * Date: 2018/05/10
     * @author Tenny
     * @param $city_id
     * @return \Illuminate\Database\Eloquent\Collection|static[]
     */
    public function getDistricts($city_id = false)
    {
        if ($city_id !== false) {
            $this->where('city_id', '=', $city_id);
        }
        $redis_key = sprintf('GET_DISTRICTS_LISTS_V1_%d', (int)$city_id);
        if (!Redis::exists($redis_key)) {
            $areas = $this->get();
            Redis::setex($redis_key, self::REDIS_EXPIRES_FOR_WEEKS, json_encode($areas));
        } else {
            $res = Redis::get($redis_key);
            $areas = json_decode($res);
        }

        return $areas;
    }

    protected function serialization(array $attributes)
    {
        // TODO: Implement serialization() method.
    }
}